package com.tencreat.mq;

import com.rabbitmq.client.Channel;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.OrderVO;
import com.tencreat.service.mall.IMallOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Objects;

/**
 * 取消订单消息的处理者
 * Created by macro on 2018/9/14.
 */
@Component
@RabbitListener(queues = "base-mall.order.cancel.delayed.cancel.name")
public class CancelOrderConsumer {
    private static Logger LOGGER =LoggerFactory.getLogger(CancelOrderConsumer.class);
    @Autowired
    private IMallOrderService mallOrderService;

    @RabbitHandler(isDefault=true)
    public void handle(Message message, Channel channel) throws Exception{
        LOGGER.info("进入订单取消mq队列--------------------------------------");
        ByteArrayInputStream byteInt = new ByteArrayInputStream(message.getBody());
        ObjectInputStream objInt = new ObjectInputStream(byteInt);
        OrderVO orderVO = (OrderVO) objInt.readObject();

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //信息为空,丢弃该信息
        if (Objects.isNull(orderVO)) {
            LOGGER.info("消息为空,手动丢弃该消息....");
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        LOGGER.info("receive delay message orderSn:{}",orderVO.getOrderSn());
        HttpResult<Boolean> booleanHttpResult = mallOrderService.cancelOrder(orderVO);
        if (booleanHttpResult.getCode() == HttpResult.ok().getCode() && booleanHttpResult.getData()){
            channel.basicAck(deliveryTag, false);
        }
    }
}
